package poland;

import java.util.Stack;

public class Calc {

	public class State {
		public Stack<Expression> stack = new Stack<Expression>();
		public double total = 0.0;
	}

	private State state;

	public Calc() {
		state = new State();
	}

	public void clearState() {
		state = new State();
	}

	/**
	 * checks input then calculates its value
	 * 
	 * @param expression
	 * @return the result of processing the string as RPN
	 * @throws Exception
	 */
	public Expression process(String expression) throws Exception {
		for (String tok : expression.split(" ")) {
			processToken(tok);
		}

		Expression last = state.stack.pop();

		if (!state.stack.isEmpty())
			throw new Exception();

		last.setTopMost(true);
		return last;
	}

	/**
	 * handling tokenized strings if digit then push if op then do the op on
	 * last two digits
	 */

	void processToken(String token) {
		if (token.length() > 0) {
			if (Character.isDigit(token.charAt(0))) {
				state.stack.push(new NumericExpression(token) {
				});
			} else if (CompoundExpression.isOperator(token)) {
				Expression ex1 = state.stack.pop(); // in case of empty stack
													// will throw exception,
													// which is good
				Expression ex2 = state.stack.pop();

				state.stack.push(new CompoundExpression(token, ex2, ex1));
			}
		}
	}
}